"""
Processes mails and triggers sending.
"""

import logging

class MailProcessor:
    '''
    Processes emails for single group - set of processors. 
   
    It either processes common email sending or individual mails to developers.
    '''

    def __init__(self, settings, mail_sender):
        '''
        Creates the processor.
        
        setings: settings object
        mail_sender: the object used to send emails
        '''
        self._mail_sender = mail_sender
        self._settings = settings
        
    def process_common_mail(self, subject, processors, send_to_all_in_group):
        """
        Processes emails to be sent to common destination for all repositories.
        
        subject: subject of the mail
        processors: list of all processors to be sent in the group
        send_to_all_in_group: send mail also to all developers who made commits for the whole group
        
        """
        emails = set()
        emails.update(self._settings.SENDALL_TO)
        if send_to_all_in_group:
            for processor in processors:
                emails.update(processor.emails)
        html = self._mail_sender.send_mail(emails, subject, processors)
        logging.info("Sent mail to " + str(self._settings.SENDALL_TO))
        logging.debug(html)
        logging.debug("=" * 80)
    
    def process_emails_to_individuals(self, subject, processors):
        """
        Processes emails and triggers sending to individual developers.
        
        subject: subject of the mail
        processors: list of all processors
        """
        emails = set()
        email_processors = {}
        for processor in processors:
            emails.update(processor.emails)
        for email in emails:
            if email not in self._settings.SENDALL_TO:
                email_processors[email] = \
                    [processor for processor in processors \
                        if email in processor.emails]
        for email, my_processors in email_processors.iteritems():
            total_changes = 0
            for processor in my_processors:
                total_changes += len(processor.changes)
            if (total_changes != 0):
                mails = set()
                mails.add(email)
                html = self._mail_sender.send_mail(mails, subject, my_processors)
                logging.info("Sent mail to " + str(email))
                logging.debug(html)
                logging.debug("=" * 80)
